<template>
  <div class="app-task-list">
    <div class="app-list-item">
      <v-list>
        <v-list-item-group>
          <v-list-item
            v-for="item in newcollect"
            :key="item.id"
            class="list-item-task"
            v-if="item.showCheckbox != false"
          >
            <v-checkbox
              class="mr-3 ml-1"
              @click="completeTask(item)"
              color="success"
              v-model="item.statusCode"
            ></v-checkbox>
            <v-row @click="toDetails(item)" style="transform: translateY(-2px)">
              <span
                ><span
                  class="taskType"
                  :style="'background-color:'+getTypeText(item,'color')"
                  >{{ getTypeText(item,'text') }}</span
                ></span
              >
              <span class="task-context">{{ item.name }}</span>
              <!--是否有任务描述  显示图标（有），不显示图标（无）-->
              <span v-if="item.hasdetail == 1"
                ><i class="fa fa-file-text-o fa-fw"></i
              ></span>
              <span v-if="item.replycount > 0">
                <i class="fa fa-comment-o fa-fw"></i>
              </span>
              <!--评论总条数-->
              <span>{{ item.replycount > 0 ? item.replycount : "" }}</span>
            </v-row>
            <!--                截止时间-->
            <v-col class="text-right col-endtime" cols="3" sm="11">
              <el-dropdown
                trigger="click"
                placement="bottom-start"
                :class="['taskendtime']"
                @visible-change="show($event, item)"
              >
                <span
                  :class="[
                    'el-dropdown-link',
                    new Date(item.deadline) < new Date(getDate()) &&
                    item.deadline
                      ? 'taskactive'
                      : '',
                  ]"
                  v-if="item.deadline"
                >
                  {{ dateFormat(item.deadline) }}
                </span>

                <span
                  :class="[
                    'el-dropdown-link',
                    'settime',
                    item.changeModel ? 'active' : '',
                    'taskendtime',
                    new Date(item.deadline) < new Date(getDate()) &&
                    item.deadline
                      ? 'taskactive'
                      : '',
                  ]"
                  v-else
                >
                  设置截止时间
                </span>
                <el-dropdown-menu slot="dropdown">
                  <el-dropdown-item>
                    <v-date-picker
                      v-model="item.deadline"
                      :allowed-dates="allowedDates"
                      :first-day-of-week="0"
                      locale="zh-cn"
                      no-title
                      scrollable
                      @change="
                        (val) => {
                          updateTaskById({ deadline: val ? val : '' }, item);
                        }
                      "
                    >
                      <!-- <v-btn style="color:red;left:80%;background-color:transparent;border:0px" color="primary" @click="$refs.menu.save(date)"
                        >清空</v-btn
                      > -->
                      <v-btn
                        text
                        small
                        class="picker-btn"
                        @click="
                          () => {
                            updateTaskById({ deadline: '' }, item),
                              (item.deadline = '');
                          }
                        "
                        >清空</v-btn
                      ></v-date-picker
                    >
                  </el-dropdown-item>
                </el-dropdown-menu>
              </el-dropdown>
            </v-col>

            <div class="icon-principal-select">
              <app-tasklist-avatar
                :item="item"
                :taskTeamMemberMetaShow="taskTeamMemberMetaShow"
                :userslist="userslist"
                :viewState="viewState"
                :changeModel="item.changeModel"
                @changeModelStatus="changeModelStatus($event, item)"
                @updateTaskStatus="updateTaskStatus"
              ></app-tasklist-avatar>
            </div>
          </v-list-item>
        </v-list-item-group>
      </v-list>
      <app-projectinfo-form
        :context="context"
        v-show="!displayMode"
        :userslist="userslist"
        :taskTeamMemberMetaShow="taskTeamMemberMetaShow"
        :typeMetaShow="typeMetaShow"
        @createTask="createTask"
        @changedisplaymodel="changedisplaymodel"
      ></app-projectinfo-form>
    </div>
  </div>
</template>

<script lang="tsx">
import {
  Vue,
  Component,
  Prop,
  Provide,
  Emit,
  Watch,
  Model,
  Inject,
} from "vue-property-decorator";
import { ControlInterface } from "@/interface/control";
import { Subject, Subscription } from "rxjs";
import { UIActionTool, Util, ViewTool } from "@/utils";
import TaskService from "@/service/task/task-service";
import UsersService from "@/service/user/user-service";
import CodeListService from "@/codelist/codelist-service";
import ProjectTeamServiceBase from "@service/project-team/project-team-service-base";

@Component({
  components: {},
})
export default class AppTaskList extends Vue {
  /**
   * 视图通讯对象
   *
   * @type {Subject<ViewState>}
   * @memberof AppTaskList
   */
  @Prop() public viewState!: Subject<ViewState>;

  /**
   * 显示状态
   *
   * @param {boolean} visable
   * @param {any} item
   * @memberof AppTaskList
   */
  public show(visable: boolean, item: any) {
    item.changeModel = visable;
    this.$forceUpdate();
  }

  /**
   * 子组件通知执行的函数
   *
   * @param {any} val
   * @param {any} item
   * @memberof AppTaskList
   */
  public changeModelStatus(val: any, item: any) {
    item.changeModel = val.visable;
    this.$forceUpdate();
  }

  /**
   * 视图参数
   *
   * @type {any}
   * @memberof AppTaskList
   */
  @Prop() public viewparams: any;

  /**
   * 任务列表数据
   *
   * @type {any}
   * @memberof AppTaskList
   */
  @Prop() public items: any;

  /**
   * 应用上下文
   *
   * @type {any}
   * @memberof AppTaskList
   */
  @Prop() public context: any;

  /**
   * 项目团队成员信息
   *
   * @type {any}
   * @memberof AppTaskList
   */
  public taskTeamMemberMetaShow: any = [];

  /**
   * 全部用户信息
   *
   * @type {any}
   * @memberof AppTaskList
   */
  public userslist: any = [];

  /**
   * 代码表服务对象
   *
   * @type {CodeListService}
   * @memberof AppVuetifyAutocompletes
   */

  public codeListService: CodeListService = new CodeListService({
    $store: this.$store,
  });

  /**
   * 表单显示状态
   *
   * @type {any}
   * @memberof AppTaskList
   */
  @Prop() public displayMode: any;

  /**
   * 项目团队对象
   *
   * @type {ProjectTeamServiceBase}
   * @memberof AppTaskList
   */
  public projectTeamServiceBase: ProjectTeamServiceBase = new ProjectTeamServiceBase();

  /**
   * 优先级代码项
   * @type {Array<any>}
   * @memberof AppTaskList
   */
  public typeMetaShow: Array<any> = [];

  /**
   * Vue声明周期，组件创建完毕
   *
   * @memberof AppTaskList
   */
  public created() {
    this.getCodeList();
    // 优先级代码表
    let typeCodelist = this.getTypeCodelist();
    this.typeMetaShow = typeCodelist;
    this.newItems();
    this.$emit("apptasklist", "created");
  }

  /**
   * 列表数据
   *
   * @memberof AppTaskList
   */
  public newcollect: any = [];

  /**
   *分页对象
   *
   *@memberof AppTaskList
   */
  private page: any = {
    size: 1000,
    page: 0,
  };

  /**
   * 获取优先级代码表
   *
   * @memberof AppTaskList
   * @return 代码表数组
   */
  public getTypeCodelist() {
    const codelist = this.$store.getters.getCodeList("Task__type");
    if (codelist) {
      let items: Array<any> = [...JSON.parse(JSON.stringify(codelist.items))];
      return items;
    } else {
      console.log(`----Action__type----代码表不存在`);
      return [];
    }
  }

  /**
   * 代码表转换
   * @param {string} [item] 代码项
   * @memberof AppTaskdetail
   * @return 代码项text值
   */
  public getTypeText(item: any,type: any) {
    let val = "";
    for (let i = 0; i < this.typeMetaShow.length; i++) {
      if (this.typeMetaShow[i].id == item.type) {
        if(Object.is(type,'text'))
          val = this.typeMetaShow[i].label;
        else
          val = this.typeMetaShow[i].color;
      }
    }
    return val;
  }

  /**
   * 将数据进行排序
   *
   * @memberof AppTaskList
   */
  public newItems() {
    this.items.forEach((item: any) => {
      // if (item.status == "已完成") {
      //   item.statusCode = true;
      //   this.newcollect.push(item);
      //   return;
      // }
      // item.statusCode = false;
      // this.newcollect.unshift(item);
      if (item.status == "done") item.statusCode = true;
      else item.statusCode = false;

      this.newcollect.push(item);
    });
  }

  /**
   * 获取动态代码表UserRealName
   *
   * @memberof AppTaskList
   */
  public async getCodeList() {
    let codeList: any = this.codeListService.getItems("UserRealName");
    await codeList
      .then((items: any) => {
        if (items && items.length > 0) {
          this.userslist.push(...items);
        }
        this.viewState.next({
          tag: "",
          action: "avatar",
          data: {},
        });
      })
      .catch((error: any) => {
        console.log(error);
      });
    await this.getTaskTeam();
  }

  /**
   * 设置日期选择不能选择以前的日期
   *
   * @param {any} val
   * @returns {any}
   * @memberof AppTaskList
   */
  public allowedDates(val: any): any {
    return Date.parse(val) > Date.now() - 8.64e7;
  }

  /**
   * 打开详情
   *
   * @param {any} id
   * @memberof AppTaskList
   */
  public toDetails(item: any) {
    this.$emit("todetails", item);
  }

  /**
   * 将时间转换成~月~日格式
   * @param {any} time
   * @memberof AppTaskList
   */
  public dateFormat(time: any) {
    var date = new Date(time);
    var month = date.getMonth() + 1;
    var day = date.getDate() < 10 ? "0" + date.getDate() : date.getDate();
    return month + "月" + day + "日";
  }

  /**
   * 获取项目团队成员清单
   *
   * @memberof AppProjectinfoHeader
   */
  public async getTaskTeam() {
    let context: any = {};
    let params: any = {
      srfparentdename: "Project",
      srfparentkey: this.context.project,
      project: this.context.project,
      multiple: 0,
      n_root_eq: this.context.project,
    };

    Object.assign(params, this.page);
    await this.projectTeamServiceBase
      .FetchDefault(context, params, true)
      .then((response: any) => {
        if (response && response.status === 200) {
          if (response.data) {
            this.taskTeamMemberMetaShow = [];
            let no_member = { icon: "", value: 0, label: "无负责人" };
            this.taskTeamMemberMetaShow.push(no_member);
            for (let i = 0; i < response.data.length; i++) {
              let account = response.data[i].account;
              // let avatar = response.data[i].avatar;
              //let avatar = response.data[i].account;
              // let realname = response.data[i].realname;
              let realname = response.data[i].account;
              let commiter = response.data[i].commiter;
              this.userslist.forEach((useritme: any) => {
                if (Object.is(useritme.value, account)) {
                  realname = useritme.label;
                }
              });
              let member: any = {
                value: account,
                label: realname,
                commiter: commiter,
              };

              this.taskTeamMemberMetaShow.push(member);
            }
          }
        }
      })
      .catch((e: any) => {
        if (e && e.status === 500) {
          const url: any = "/500";
          this.$router.push({ path: url });
        } else {
          this.$Notice.error({
            title: "错误",
            desc: e.data.message,
          });
        }
      });
  }
  /**
   * 子组件创建任务成功通知
   *
   * @param {any} val
   * @memberof AppTaskList
   */
  public createTask(val: any) {
    let task: any = {
      isselected: false,
      srfkey: val.id,
      srfmajortext: val.name,
      srfuf: 1,
      status: "doing",
      statusCode: false,
      task: val.id,
    };
    Object.assign(val, task);
    this.newcollect.unshift(val);
    this.$nextTick(() => {
      this.viewState.next({
        tag: "",
        action: "avatar",
        data: this.taskTeamMemberMetaShow,
      });
    });
    //通知关闭form表单
    this.$emit("displaychange", {});
    this.$forceUpdate();
  }

  /**
   * 点击完成任务（当任务未完成时）,点击激活任务（当任务已完成时）
   *
   * @param {any} item
   * @memberof AppTaskList
   */
  public completeTask(item: any) {
    this.$emit("completetask", JSON.parse(JSON.stringify(item)));
  }

  /**
   * 更新任务
   *
   * @param {any} json
   * @param {any} item
   * @memberof AppTaskList
   */
  public async updateTaskById(json: any, item: any) {
    this.$emit("updatetaskbyid", {
      json: JSON.parse(JSON.stringify(json)),
      item: JSON.parse(JSON.stringify(item)),
    });
  }

  /**
   * 重新指派成功修改任务显示状态
   *
   * @param {any} id
   * @memberof AppTaskList
   */
  public updateTaskStatus(id: any) {
    // this.newcollect.forEach((item: any) => {
    //   if (Object.is(item.id,id)) {
    //     item.statusCode = false;
    //     this.$forceUpdate();
    //   }
    // });
  }

  /**
   * form表单取消通知事件
   *
   * @memberof AppTaskList
   */
  public changedisplaymodel() {
    this.$emit("displaychange", {});
  }

  /**
   * 获取当前日期
   *
   * @memberof AppTaskList
   */
  public getDate(): any {
    var newDate = new Date();
    var month =
      newDate.getMonth() < 9
        ? "0" + (newDate.getMonth() + 1)
        : newDate.getMonth() + 1;
    var date =
      newDate.getDate() <= 9 ? "0" + newDate.getDate() : newDate.getDate();

    return newDate.getFullYear() + "-" + month + "-" + date;
  }
}
</script>

<style lang="less">
@import "./app-task-list.less";
</style>
